package com.example.lets;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.bmob.BTPFileResponse;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.UploadListener;
import com.widget.CircleImageView;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.datatype.BmobFile;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;


public class CompleteInfoActivity extends Activity {

    private SelectPicPopupWindow selWindow; // �Զ���ĵ�������  
    private Uri                  photoUri = null;
    private String               fileName = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_complete_info);
		
		fileName = null;

		final CheckBox boxFemale = (CheckBox) CompleteInfoActivity.this.findViewById(R.id.complete_info_female);
		final CheckBox boxMale = (CheckBox) CompleteInfoActivity.this.findViewById(R.id.complete_info_male);
		
		boxFemale.setOnClickListener(new CheckBox.OnClickListener(){
			@Override
			public void onClick(View v) {
				if(boxMale.isChecked()){
					boxMale.setChecked(false);
				}
			}
		});
		boxMale.setOnClickListener(new CheckBox.OnClickListener(){
			@Override
			public void onClick(View v) {
				if(boxFemale.isChecked()){
					boxFemale.setChecked(false);
				}
			}
		});

		CircleImageView upload = (CircleImageView) this.findViewById(R.id.complete_info_portrait);
		upload.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) { // �������Դ������ѡ��ͼƬ

                selWindow = new SelectPicPopupWindow(CompleteInfoActivity.this, new OnClickListener() {  
                	// Ϊ��������ʵ�ּ�����  
                    public void onClick(View v) { 
                    	
                    	selWindow.dismiss();
                    	
                        int id = v.getId();
						if (id == R.id.btn_take_photo) {
							SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
							String filename = "Lets_Head_" + timeStampFormat.format(new Date());
							ContentValues values = new ContentValues();
							values.put(Media.TITLE, filename);
							Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
							intent1.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
							startActivityForResult(intent1, 1);
						} else if (id == R.id.btn_pick_photo) {
							Intent intent2 = new Intent();
                            intent2.setType("image/*");
                            intent2.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(intent2, 2);
						} else {
							Log.i("bmob", "undefined button");
							Toast.makeText(CompleteInfoActivity.this, "未定义的按钮！", Toast.LENGTH_SHORT).show();
						}     
                    }    
                });

                selWindow.showAtLocation(CompleteInfoActivity.this.findViewById(R.id.complete_view), 
                		                 Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); // ����layout��PopupWindow����ʾ��λ��
			}
		});

		Button save = (Button) this.findViewById(R.id.complete_info_save);
		save.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				if (fileName == null || fileName.equals("")) {
					Log.i("bmob", "头像不存在！");
					Toast.makeText(CompleteInfoActivity.this, "头像不存在！", Toast.LENGTH_SHORT).show();
					return;
				}
				
				String gender = (boxMale.isChecked()) ? "male" : "female";
				String userName = ((EditText) CompleteInfoActivity.this.findViewById(R.id.complete_info_username)).getText().toString();
				Integer age = new Integer(0);
				
				if (userName == null || userName.equals("")) {
					Toast.makeText(CompleteInfoActivity.this, "请输入用户名！", Toast.LENGTH_SHORT).show();
					return;
				}

				if(userName.length() > 12){
					Toast.makeText(CompleteInfoActivity.this, "用户昵称过长，请限制在12个字符以内", Toast.LENGTH_SHORT).show();
					return;
				}

				if (!boxMale.isChecked() && !boxFemale.isChecked()) { 
					Toast.makeText(CompleteInfoActivity.this, "性别不明！", Toast.LENGTH_SHORT).show();
					return;
				}

				try {
					age = Integer.parseInt(((EditText) CompleteInfoActivity.this.findViewById(R.id.complete_info_age)).getText().toString());
				} catch (NumberFormatException e) {
					Toast.makeText(CompleteInfoActivity.this, "请输入正确的年龄！", Toast.LENGTH_SHORT).show();
				}

				if (age <= 0 || age >= 100) {
					Toast.makeText(CompleteInfoActivity.this, "请输入正确的年龄！", Toast.LENGTH_SHORT).show();
					return;
				}
				
				String tag1 = ((EditText) CompleteInfoActivity.this.findViewById(R.id.complete_info_tag1)).getText().toString();
				String tag2 = ((EditText) CompleteInfoActivity.this.findViewById(R.id.complete_info_tag2)).getText().toString();
				String tag3 = ((EditText) CompleteInfoActivity.this.findViewById(R.id.complete_info_tag3)).getText().toString();
				
				completeInfo(userName, gender, age, tag1, tag2, tag3);
			}
		});
	}


	@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case 1: //
			if (resultCode == RESULT_OK) {
				Uri uri = null;
				if (data != null && data.getData() != null)
					uri = data.getData(); // �ü�ͼƬ
				else if (photoUri != null)
					uri = photoUri;
				else {
					Toast.makeText(this, "照取图片出错！", Toast.LENGTH_SHORT);
					Log.i("bmob", "照取图片出错！");
				}
				cropPhoto(uri); // �ü�ͼƬ
			}
			break;
			
		case 2: //
			if (data != null) {
				Uri uri = data.getData();
				cropPhoto(uri); // �ü�ͼƬ
	            Log.e("uri", uri.toString());
			}
			else {
				Log.i("bmob", "图片不存在！");
				Toast.makeText(this, "图片不存在！", Toast.LENGTH_SHORT);
			}
			break;
			
		case 3: //
			if (data != null) {
				Bundle extras = data.getExtras();
				Bitmap head = extras.getParcelable("data");
				if(head != null) {
					setPicToView(head); // ������SD����
					ImageView imageView = (ImageView) findViewById(R.id.complete_info_portrait); 
	                imageView.setImageBitmap(head); // ��Bitmap�趨��ImageView
				}
			}
			break;
			
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
    }
	
	// ����ϵͳ�ü�
	public void cropPhoto(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}
	
	// 将mBitmap保存在SD卡中
	private void setPicToView(Bitmap mBitmap) {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // ���sd�Ƿ����
			return;
		}
		FileOutputStream b = null;
		String path = "/sdcard/Lets/myHead/";
		File file = new File(path);
		if (!file.exists())
			file.mkdirs(); // �����ļ���
		
		User curUser = BmobUser.getCurrentUser(this, User.class);
		fileName = path + curUser.getUsername() + "_head.jpg"; //ͼƬ����
		try {
			b = new FileOutputStream(fileName);
			mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b); // ������д���ļ�
			Log.i("bmob", "成功写入图片文件至" + fileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			Log.i("bmob", e.getMessage());
		} finally {
			try { //�ر���
				b.flush();
				b.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void completeInfo(String userName, String gender, Integer age, String tag1, String tag2, String tag3){
		
		final User curUser = BmobUser.getCurrentUser(this, User.class);
		if (curUser != null) {
			
			Log.d("bmob", "getObjectId = " + curUser.getObjectId());
			Log.d("bmob", "getUsername = " + curUser.getUsername());
			Log.d("bmob", "getEmail = "    + curUser.getEmail());
			
			final User newUser = new User();
			newUser.setNickname(userName);
			newUser.setAge(age);
			newUser.setGender(gender);
			newUser.setTag1(tag1);
			newUser.setTag2(tag2);
			newUser.setTag3(tag3);
			
			File file = new File(fileName);
			if (!file.exists()) {
				Log.e("bmob", "头像文件不存在！");
				Toast.makeText(this, "头像文件不存在！", Toast.LENGTH_SHORT);
				return;
			}
			
			BTPFileResponse response = BmobProFile.getInstance(this).upload(fileName, new UploadListener() {

	            @Override
	            public void onSuccess(String fileName, String url, BmobFile file) {
	                Log.i("bmob", "文件上传成功：" + fileName + ",可访问的文件地址：" + file.getUrl());
					newUser.setPicture(file);
	                newUser.setPicFilename(fileName);
	                newUser.update(CompleteInfoActivity.this, curUser.getObjectId(), new UpdateListener(){
	    				@Override
	    				public void onFailure(int arg0, String arg1) {
	    					// TODO Auto-generated method stub
	    					Toast.makeText(CompleteInfoActivity.this, "完善失败", Toast.LENGTH_SHORT).show();
	    				}

	    				@Override
	    				public void onSuccess() {
	    					// TODO Auto-generated method stub
	    					Toast.makeText(CompleteInfoActivity.this, "完善成功", Toast.LENGTH_SHORT).show();
	    					Intent intent = new Intent();
	    					intent.setClass(CompleteInfoActivity.this, HomeActivity.class);
	    					startActivity(intent);
	    					CompleteInfoActivity.this.finish();
	    				}
	    			});
	            }

	            @Override
	            public void onProgress(int progress) {
	                // TODO Auto-generated method stub
	                Log.i("bmob","onProgress :" + progress);
	            }

	            @Override
	            public void onError(int statuscode, String errormsg) {
	                // TODO Auto-generated method stub
	                Log.i("bmob","文件上传失败：" + errormsg);
	            }
	        });
		} else {
			Toast.makeText(CompleteInfoActivity.this, "还未登陆", Toast.LENGTH_SHORT).show();
		}
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.complete_info, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		Intent intent= new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
		startActivity(intent);
		return;
	}
}
